# -*- decode:utf-8 -*-
import hashlib
from datetime import datetime, timedelta
from re import findall, match


def extract(datas, map_str):
    """
    获取指定路径的数据
    :param datas: 初始数据
    :param map_str: 数据路径
    :return: object
    """
    ett_data = datas
    map_list = map_str.split(".")
    for mp in map_list:
        datas_type = type(ett_data)
        if datas_type == dict and ett_data:
            ett_data = ett_data.get(mp, dict())
        else:
            ett_data = str()
            break
    return ett_data


def extract_data(datas, map_data, map_host=None):
    """
    通过映射提取需要的数据
    :param datas: 基础数据
    :param map_data: 映射数据
    :param map_host: 映射路径
    :return: dict
    """
    ett_data = dict()
    if map_host:
        datas = extract(datas, map_host)
    for mp in map_data:
        values = extract(datas, map_data[mp])
        values = values.replace(" ", "").replace("'", '"').replace(',', "，")
        if values not in ["", "-", "null", None]:
            ett_data[mp] = values
    return ett_data


def join_dict_data(dict1, dict2, break_list=None):
    """
    dict2内容合并到dict1
    :param dict1:
    :param dict2:
    :param break_list:
    :return:
    """
    break_list = break_list if break_list else list()
    for d in dict2:
        if d not in break_list:
            value = dict2[d]
            if value:
                value1 = dict1.get(d, "")
                if len(value1) < len(value):
                    dict1[d] = value


def extract_number(strs):
    """
    提取数字+去重
    :param strs:
    :return: set
    """
    return set(findall(r"\d*", strs))


def extract_email(strs):
    """
    提取邮箱+去重
    :param strs:
    :return: set
    """
    return set(findall(r"[A-Za-z0-9_-]+@[a-zA-Z0-9_-]+.[a-zA-Z0-9_-]+", strs))


def extract_phone(strs):
    """
    提取电话
    :param strs:
    :return: set
    """
    return set(findall(
        r"13[0-9]\d{8}|14[01456879]\d{8}|15[0-35-9]\d{8}|16[2567]\d{8}|17[0-8]\d{8}|18[0-9]\d{8}|19[0-35-9]\d{8}",
        strs))


def extract_regular_phone(strs):
    """
    提取固话
    :param strs:
    :return: str
    """
    return set(findall(r"0\d{2,3}-\d{7,8}", strs))


def extract_hanzi(strs):
    """
    提取首个汉字集
    :param strs:
    :return:
    """
    r = match(".*?([\u4e00-\u9fa5]+)", strs)
    if r:
        return r.group(1)
    return str()


def extract_date(strs):
    """
    提取年月日部分，只管提取不管时间是否正确
    :param strs:
    :return:
    """
    r = match(r".*(\d{4})\D(\d{1,2})\D(\d{1,2})", strs)
    if r:
        y = r.group(1)
        m = r.group(2)
        d = r.group(3)
        return f"{y}-{m}-{d}"
    return None


def change_money(strs):
    """
    提前时间并进行转换，单位元
    :param strs:
    :return: float
    """
    r = match(r".*?([1-9]\d*[.]{0,1}\d*)", strs)
    money = None
    if r:
        money = float(r.group(1))
        w_count = strs.count("万")
        if w_count:
            money *= 10000 ** w_count
        if "亿" in strs:
            # 公司资产以亿亿为单位 前所未见，出现亿最多就1次
            money *= 100000000
    return money


def date_change_time(date_str):
    """
    时间转换为时间戳 格式 "%Y-%m-%d"
    非指定格式传入当垃圾数据处理
    :param date_str: 时间戳（毫秒）
    :return: 时间戳（毫秒）
    """
    if date_str:
        try:
            cd = datetime.strptime(date_str, "%Y-%m-%d")
            tms = (cd - datetime(1970, 1, 1)).total_seconds()
            return int(tms * 1000)
        except Exception as e:
            print(f"报错：{e}")
    return None


def time_change_date(date_str):
    """
    时间戳转换成 "%Y-%m-%d"
    :param date_str:
    :return: str
    """
    if date_str:
        try:
            dt = datetime(1970, 1, 1) + timedelta(seconds=date_str / 1000)
            return str(dt).split(" ")[0]
        except Exception as e:
            print(f"报错：{e}")
    return 0


def set_md5(value):
    """
    设置md5
    :param value:
    :return:
    """
    md5 = hashlib.md5()
    md5.update(value.encode('utf-8'))
    return md5.hexdigest()


def del_dict_keys(data, key_list):
    """
    批量删除字典里面的keys
    :param data:
    :param key_list:
    :return:
    """
    for key in key_list:
        if key in data:
            del data[key]
